import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import DiscountModel from '../../../../models/DiscountModel.js';
import DiscountCollectionView from './DiscountCollectionView.js';
import DiscountFormPopupView from './DiscountFormPopupView.js';
import ErrorView from 'base/views/ErrorView.js';
import {
    displayServerSuccess,
    displayServerError
} from 'backbone-tools.js';

const DiscountComponent = Mn.View.extend({
    tagName: 'div',
    className: 'form-section discount-group',
    template: require('./templates/DiscountComponent.mustache'),
    regions: {
        lines: {
            el: '.lines',
            replaceElement: true
        },
        'modalRegion': '.modalregion',
        'errors': ".block-errors",
    },
    ui: {
        add_button: 'button.btn-add'
    },
    triggers: {
        "click @ui.add_button": "line:add"
    },
    childViewEvents: {
        'line:edit': 'onLineEdit',
        'line:delete': 'onLineDelete',
        'destroy:modal': 'render',
        'insert:percent': 'onInsertPercent',
    },
    collectionEvents: {
        'change': 'hideErrors',
        'validated:invalid': "showErrors",
        'validated:valid': "hideErrors",
        'sync': 'render'
    },
    initialize: function (options) {
        this.collection = options['collection'];
        this.listenTo(this.collection, 'validated:invalid', this.showErrors);
        this.listenTo(this.collection, 'validated:valid', this.hideErrors.bind(this));
        this.edit = options['edit'];
        this.compute_mode = Radio.channel('config').request('get:options', 'compute_mode');
    },
    showErrors(model, errors) {
        this.detachChildView('errors');
        this.showChildView('errors', new ErrorView({
            errors: errors
        }));
        this.$el.addClass('error');
    },
    hideErrors(model) {
        this.detachChildView('errors');
        this.$el.removeClass('error');
    },
    isEmpty: function () {
        return this.collection.length === 0;
    },
    onLineAdd: function () {
        var model = new DiscountModel();
        this.showDiscountLineForm(model, "Ajouter une remise", false);
    },
    onLineEdit: function (childView) {
        this.showDiscountLineForm(childView.model, "Modifier une remise", true);
    },
    showDiscountLineForm: function (model, title, edit) {
        var form = new DiscountFormPopupView({
            model: model,
            title: title,
            destCollection: this.collection,
            edit: edit
        });
        this.showChildView('modalRegion', form);
    },
    onDeleteSuccess: function () {
        displayServerSuccess("Vos données ont bien été supprimées");
    },
    onDeleteError: function () {
        displayServerError("Une erreur a été rencontrée lors de la " +
            "suppression de cet élément");
    },
    onLineDelete: function (childView) {
        var result = window.confirm(
            "Êtes-vous sûr de vouloir supprimer cette remise ?"
        );
        if (result) {
            childView.model.destroy({
                success: this.onDeleteSuccess,
                error: this.onDeleteError
            });
        }
    },
    onInsertPercent: function (model) {
        this.collection.insert_percent(model);
        this.getChildView('modalRegion').triggerMethod('modal:close')
    },
    templateContext: function () {
        const empty = this.isEmpty();
        return {
            not_empty: !empty,
            collapsed: empty,
            edit: this.edit,
            is_ttc_mode: this.compute_mode == 'ttc',

        }
    },
    onRender: function () {
        if (!this.isEmpty()) {
            this.showChildView(
                'lines',
                new DiscountCollectionView({
                    collection: this.collection,
                    edit: this.edit
                })
            );
        }
    }
});
export default DiscountComponent;
